// 页面切换功能
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', function (e) {
            e.preventDefault();

            // 移除所有active类
            document.querySelectorAll('.nav-item').forEach(el => {
                el.classList.remove('active');
            });

            // 添加当前active类
            this.classList.add('active');

            const page = this.getAttribute('data-page');
            showPage(page);
        });
    });

    // 刷新仪表盘
    function refreshDashboard() {
        if (window.chartInitialized) {
            initDashboardChart();
        }
    }


    // 显示错误信息
    function showError(container, message) {
        container.innerHTML = `
            <div style="display: flex; justify-content: center; align-items: center; height: 100%; color: #ff4444; flex-direction: column;">
                <i class="bi bi-exclamation-triangle" style="font-size: 48px; margin-bottom: 10px;"></i>
                <div style="font-size: 16px; margin-bottom: 5px;">图表加载失败</div>
                <div style="font-size: 14px; color: #666; margin-bottom: 15px;">${message}</div>
                <button onclick="initModelTrendTimelineChart()" style="padding: 8px 16px; background: #1e88e5; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    重新加载
                </button>
            </div>
        `;
    }

    // 初始化仪表盘图表
    function initDashboardChart() {
        // 标记图表已初始化
        window.chartInitialized = true;

        const chartDom = document.getElementById('chart');
        const myChart = echarts.init(chartDom);

        // 显示加载状态
        myChart.showLoading({
            text: '数据加载中...',
            color: '#c23531',
            textColor: '#000',
            maskColor: 'rgba(255, 255, 255, 0.8)'
        });

        // 从后端获取数据
        fetch('/get_chart_data')
                .then(response => response.json())
                .then(data => {
                    // 隐藏加载提示
                    document.getElementById('loading').style.display = 'none';
                    myChart.hideLoading();

                    // 处理数据
                    const dates = data.dates;
                    const chartData = data.data;

                    // 准备时间线选项
                    const options = dates.map(date => {
                        return {
                            title: {
                                text: `${date} 厂商销量TOP10`,
                                left: 'center'
                            },
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                },
                                formatter: function (params) {
                                    return `${params[0].name}<br/>销量: ${params[0].value}台`;
                                }
                            },
                            xAxis: {
                                type: 'category',
                                data: chartData[date].groups,
                                axisLabel: {
                                    rotate: -30,
                                    interval: 0,
                                    margin: 10
                                }
                            },
                            yAxis: {
                                type: 'value',
                                name: '销量（台）',
                                position: 'right',
                                nameTextStyle: {
                                    align: 'right',
                                    padding: [0, 0, 0, 10]
                                },
                                axisLabel: {
                                    margin: 10,
                                    formatter: function (value) {
                                        if (value >= 10000) {
                                            return (value / 10000).toFixed(1) + '万';
                                        }
                                        return value;
                                    }
                                },
                                splitLine: {
                                    show: true,
                                    lineStyle: {
                                        type: 'dashed'
                                    }
                                }
                            },
                            series: [{
                                name: '销量',
                                type: 'bar',
                                data: chartData[date].sales,
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        {offset: 0, color: '#83bff6'},
                                        {offset: 0.5, color: '#188df0'},
                                        {offset: 1, color: '#188df0'}
                                    ])
                                },
                                emphasis: {
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            {offset: 0, color: '#2378f7'},
                                            {offset: 0.7, color: '#2378f7'},
                                            {offset: 1, color: '#83bff6'}
                                        ])
                                    }
                                },
                                label: {
                                    show: true,
                                    position: 'top',
                                    formatter: '{c}',
                                    fontSize: 12,
                                    fontWeight: 'bold',
                                    color: '#333'
                                }
                            }],
                            dataZoom: [{
                                type: 'inside',
                                start: 0,
                                end: 100
                            }],
                            toolbox: {
                                feature: {
                                    saveAsImage: {
                                        title: '保存图片',
                                        pixelRatio: 2
                                    },
                                    dataView: {show: true, readOnly: false},
                                    restore: {show: true}
                                },
                                right: 20
                            },
                            grid: {
                                left: '10%',
                                right: '8%',
                                top: '18%',
                                bottom: '15%',
                                containLabel: true
                            }
                        };
                    });

                    // 设置基础配置
                    const baseOption = {
                        timeline: {
                            axisType: 'category',
                            orient: 'vertical',
                            autoPlay: true,
                            playInterval: 3000,
                            left: 10,
                            right: '1%',
                            top: 'center',
                            bottom: 'auto',
                            width: 60,
                            height: '85%',
                            data: dates,
                            label: {
                                position: 'left',
                                color: '#333',
                                fontSize: 14,
                                fontWeight: 'bold',
                                formatter: function (value) {
                                    return value.substring(2);
                                }
                            },
                            symbol: 'diamond',
                            symbolSize: 10,
                            currentIndex: 0,
                            controlStyle: {
                                itemSize: 16,
                                itemGap: 12
                            }
                        },
                        baseOption: {
                            grid: {
                                left: '10%',
                                right: '8%',
                                top: '18%',
                                bottom: '15%',
                                containLabel: true
                            }
                        },
                        options: options
                    };

                    // 渲染图表
                    myChart.setOption(baseOption);

                    // 窗口大小变化时重绘图表
                    window.addEventListener('resize', function () {
                        myChart.resize();
                    });

                    // 初始化其他图表
                    initRankingChart();
                    initMarketShareChart(); // 初始化市场份额图表
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    document.getElementById('loading').innerHTML =
                            '<div style="color:red;">数据加载失败，请刷新页面重试</div>';
                });
    }

    // 初始化年度排名图表 - 支持年份选择
    function initRankingChart() {
        const chartDom = document.getElementById('ranking-chart');

        // 确保图表容器存在
        if (!chartDom) return;

        const chart = echarts.init(chartDom);
        let selectedYear = '2023';

        // 渲染图表函数
        function renderChart(data) {
            // 检查数据有效性
            if (!data || !data.manufacturers || data.manufacturers.length === 0) {
                chart.showLoading({
                    text: '无可用数据',
                    color: '#ff6b6b',
                    textColor: '#ff0000',
                    maskColor: 'rgba(255, 255, 255, 0.8)'
                });
                return;
            }

            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {type: 'shadow'},
                    formatter: function (params) {
                        const manufacturer = params[0].name;
                        const sales = params[0].value;
                        const rank = params[0].dataIndex + 1;
                        return `<strong>${manufacturer}</strong><br/>排名: #${rank}<br/>销量: ${sales.toLocaleString()}台`;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    name: '销量（台）',
                    axisLabel: {
                        formatter: function (value) {
                            if (value >= 1000000) return (value / 1000000).toFixed(1) + 'M';
                            if (value >= 10000) return (value / 10000).toFixed(1) + '万';
                            return value;
                        }
                    }
                },
                yAxis: {
                    type: 'category',
                    axisLabel: {interval: 0, fontSize: 12},
                    data: data.manufacturers
                },
                series: [{
                    name: '销量',
                    type: 'bar',
                    data: data.sales,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            {offset: 0, color: '#83bff6'},
                            {offset: 0.7, color: '#188df0'},
                            {offset: 1, color: '#188df0'}
                        ])
                    },
                    label: {
                        show: true,
                        position: 'right',
                        formatter: (params) => params.value.toLocaleString(),
                        fontSize: 11
                    }
                }]
            };

            chart.setOption(option);
        }

        // 加载数据函数
        function loadData(year) {
            // 显示加载状态
            chart.showLoading({
                text: '数据加载中...',
                color: '#c23531',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)'
            });

            // 从后端获取数据
            fetch(`/api/ranking-data?year=${year}`)
                    .then(response => {
                        if (!response.ok) throw new Error(`网络响应错误: ${response.status}`);
                        return response.json();
                    })
                    .then(data => {
                        chart.hideLoading();

                        if (data.success && data.data[year]) {
                            renderChart({
                                manufacturers: data.data[year].manufacturers,
                                sales: data.data[year].sales
                            });
                        } else {
                            throw new Error('数据格式错误或缺少年份数据');
                        }
                    })
                    .catch(error => {
                        chart.hideLoading();
                        chart.showLoading({
                            text: '数据加载失败: ' + error.message,
                            color: '#ff6b6b',
                            textColor: '#ff0000',
                            maskColor: 'rgba(255, 255, 255, 0.8)'
                        });
                    });
        }

        // 年份选择器事件 - 只绑定到排名图表的年份按钮
        const rankingContainer = chartDom.closest('.page-container');
        rankingContainer.querySelectorAll('.year-btn').forEach(btn => {
            btn.addEventListener('click', function () {
                rankingContainer.querySelectorAll('.year-btn').forEach(b => {
                    b.classList.remove('active');
                });
                this.classList.add('active');
                selectedYear = this.getAttribute('data-year');
                loadData(selectedYear);
            });
        });

        // 初始加载数据
        loadData(selectedYear);

        // 响应式调整
        window.addEventListener('resize', () => chart.resize());
    }

    // 初始化市场份额图表 - 支持年份选择
    function initMarketShareChart() {
        const chartDom = document.getElementById('market-share-chart');

        // 确保图表容器存在
        if (!chartDom) return;

        const chart = echarts.init(chartDom);
        let selectedYear = '2023';

        // 渲染图表函数
        function renderChart(data) {
            // 检查数据有效性
            if (!data || !data.manufacturers || data.manufacturers.length === 0) {
                chart.showLoading({
                    text: '无可用数据',
                    color: '#ff6b6b',
                    textColor: '#ff0000',
                    maskColor: 'rgba(255, 255, 255, 0.8)'
                });
                return;
            }

            // 准备饼图数据
            const pieData = data.manufacturers.map((name, index) => {
                return {
                    value: data.shares[index],
                    name: name
                };
            });

            // 配置选项
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c}%'
                },
                legend: {
                    orient: 'vertical',
                    left: 10,
                    top: 'center',
                    data: data.manufacturers
                },
                title: {
                    text: `${data.year}年市场份额分析`,
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                series: [
                    {
                        name: `${data.year}年市场份额`,
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '18',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: pieData
                    }
                ]
            };

            chart.setOption(option);
        }

        // 加载数据函数
        function loadData(year) {
            // 显示加载状态
            chart.showLoading({
                text: '数据加载中...',
                color: '#c23531',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)'
            });

            // 从后端获取数据
            fetch(`/api/market-share-data?year=${year}`)
                    .then(response => {
                        if (!response.ok) throw new Error(`网络响应错误: ${response.status}`);
                        return response.json();
                    })
                    .then(data => {
                        chart.hideLoading();

                        if (data.success) {
                            renderChart({
                                year: data.year,
                                manufacturers: data.manufacturers,
                                shares: data.shares
                            });
                        } else {
                            throw new Error(data.error || '未知错误');
                        }
                    })
                    .catch(error => {
                        chart.hideLoading();
                        chart.showLoading({
                            text: '数据加载失败: ' + error.message,
                            color: '#ff6b6b',
                            textColor: '#ff0000',
                            maskColor: 'rgba(255, 255, 255, 0.8)'
                        });
                        console.error('加载市场份额数据失败:', error);
                    });
        }

        // 获取市场份额图表的年份选择器容器
        const marketShareContainer = chartDom.closest('.page-container');

        // 年份选择器事件 - 只绑定到市场份额图表的年份按钮
        marketShareContainer.querySelectorAll('.year-btn').forEach(btn => {
            btn.addEventListener('click', function () {
                // 移除所有active类
                marketShareContainer.querySelectorAll('.year-btn').forEach(b => {
                    b.classList.remove('active');
                });

                // 添加当前active类
                this.classList.add('active');

                selectedYear = this.getAttribute('data-year');
                loadData(selectedYear);
            });
        });

        // 初始加载数据
        loadData(selectedYear);

        // 响应式调整
        window.addEventListener('resize', function () {
            chart.resize();
        });
    }


function initModelManufacturerFunnelChart() {
    const chartDom = document.getElementById('manufacturer-funnel-chart');
    const chart = echarts.init(chartDom);
    const select = document.getElementById('funnel-manufacturer-select');
    chart.showLoading({ text: '加载中...' });

    fetch('/api/model-manufacturer-top10')
        .then(res => res.json())
        .then(data => {
            chart.hideLoading();
            if (!data.success) {
                chartDom.innerHTML = '<div style="color:red;">' + data.error + '</div>';
                return;
            }

            // 添加厂商到下拉框
            select.innerHTML = '';
            data.manufacturers.forEach(m => {
                const option = document.createElement('option');
                option.value = m;
                option.textContent = m;
                select.appendChild(option);
            });

            // 存储所有图表配置
            const chartConfigs = data.charts;

            // 切换图表
            function updateChart(manufacturer) {
                const config = chartConfigs[manufacturer];
                if (config) {
                    try {
                        // 解析配置字符串为JavaScript对象
                        const option = JSON.parse(config);
                        
                        // 特殊处理：将函数字符串转换为实际函数
                        if (option.tooltip && option.tooltip.formatter) {
                            option.tooltip.formatter = new Function(
                                'return ' + option.tooltip.formatter
                            )();
                        }
                        
                        chart.setOption(option);
                    } catch (error) {
                        console.error('解析图表配置失败:', error);
                        chart.clear();
                        chartDom.innerHTML = '<div style="color:red;">图表配置解析失败</div>';
                    }
                } else {
                    chart.clear();
                    chartDom.innerHTML = '<div style="color:red;">无数据</div>';
                }
            }

            select.addEventListener('change', () => {
                updateChart(select.value);
            });

            // 初始展示第一个厂商的图表
            if (data.manufacturers.length > 0) {
                updateChart(data.manufacturers[0]);
            }

            window.addEventListener('resize', () => chart.resize());
        })
        .catch(err => {
            chart.hideLoading();
            chartDom.innerHTML = '<div style="color:red;">请求失败: ' + err.message + '</div>';
        });
}

    function initModelTop10Chart() {
        const chartDom = document.getElementById('model-chart');

        if (!chartDom) {
            console.error('图表容器未找到');
            return;
        }

        const myChart = echarts.init(chartDom);

        // 显示加载状态
        myChart.showLoading({
            text: '数据加载中...',
            color: '#c23531',
            textColor: '#000',
            maskColor: 'rgba(255, 255, 255, 0.8)'
        });

        // 从后端获取数据
        fetch('/api/model-top10-data')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                myChart.hideLoading();

                if (data.success) {
                    try {
                        // 解析 JSON 数据并设置图表选项
                        const option = JSON.parse(data.chart_data);
                        myChart.setOption(option);

                        // 窗口大小变化时重绘图表
                        const resizeHandler = () => myChart.resize();
                        window.removeEventListener('resize', resizeHandler);
                        window.addEventListener('resize', resizeHandler);

                        console.log('车型前10图表加载成功');
                    } catch (parseError) {
                        console.error('解析图表数据失败:', parseError);
                        showError(chartDom, '图表数据解析失败');
                    }
                } else {
                    console.error('获取数据失败:', data.error);
                    showError(chartDom, data.error || '数据获取失败');
                }
            })
            .catch(error => {
                console.error('网络请求失败:', error);
                myChart.hideLoading();
                showError(chartDom, '网络请求失败: ' + error.message);
            });
    }

        // 高级查询页面逻辑
    function initAdvancedQueryPage() {
        // 获取DOM元素
        const manufacturerSelect = document.getElementById('manufacturer-select');
        const modelSelect = document.getElementById('model-select');
        const yearSelect = document.getElementById('year-select');
        const queryBtn = document.getElementById('query-button');
        const dataLoading = document.getElementById('data-loading');
        const errorMessage = document.getElementById('error-message');
        const resultContainer = document.getElementById('query-result');

        // 加载厂商列表
        fetch('/api/manufacturers')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 清空现有选项（保留第一个选项）
                    while (manufacturerSelect.options.length > 1) {
                        manufacturerSelect.remove(1);
                    }

                    // 添加新选项
                    data.manufacturers.forEach(manufacturer => {
                        const option = document.createElement('option');
                        option.value = manufacturer;
                        option.textContent = manufacturer;
                        manufacturerSelect.appendChild(option);
                    });
                } else {
                    console.error('加载厂商列表失败:', data.error);
                    errorMessage.textContent = '加载厂商列表失败: ' + (data.error || '未知错误');
                    errorMessage.style.display = 'block';
                }
            })
            .catch(error => {
                console.error('加载厂商列表失败:', error);
                errorMessage.textContent = '加载厂商列表失败: ' + error.message;
                errorMessage.style.display = 'block';
            });

        // 厂商选择变化时加载车型
        manufacturerSelect.addEventListener('change', function() {
            const manufacturer = this.value;

            // 重置车型和年份选择
            modelSelect.disabled = true;
            modelSelect.innerHTML = '<option value="">-- 请选择车型 --</option>';
            yearSelect.value = '';
            queryBtn.disabled = true;
            resultContainer.style.display = 'none';

            if (manufacturer) {
                dataLoading.style.display = 'block';
                errorMessage.style.display = 'none';

                // 加载车型列表
                fetch(`/api/models?manufacturer=${encodeURIComponent(manufacturer)}`)
                    .then(response => response.json())
                    .then(data => {
                        dataLoading.style.display = 'none';

                        if (data.success) {
                            // 清空现有选项（保留第一个选项）
                            modelSelect.innerHTML = '<option value="">-- 请选择车型 --</option>';

                            // 添加新选项
                            data.models.forEach(model => {
                                const option = document.createElement('option');
                                option.value = model;
                                option.textContent = model;
                                modelSelect.appendChild(option);
                            });

                            modelSelect.disabled = false;
                        } else {
                            throw new Error(data.error || '获取车型数据失败');
                        }
                    })
                    .catch(error => {
                        dataLoading.style.display = 'none';
                        console.error('加载车型列表失败:', error);
                        modelSelect.innerHTML = '<option value="">-- 加载车型失败 --</option>';
                        errorMessage.textContent = '加载车型列表失败: ' + error.message;
                        errorMessage.style.display = 'block';
                    });
            }
        });

        // 车型选择变化时加载年份
        modelSelect.addEventListener('change', function() {
            const manufacturer = manufacturerSelect.value;
            const model = this.value;

            // 重置年份选择
            yearSelect.innerHTML = '<option value="">-- 请选择年份 --</option>';
            queryBtn.disabled = true;
            resultContainer.style.display = 'none';

            if (manufacturer && model) {
                dataLoading.style.display = 'block';
                errorMessage.style.display = 'none';

                // 加载年份列表
                fetch(`/api/years?manufacturer=${encodeURIComponent(manufacturer)}&model=${encodeURIComponent(model)}`)
                    .then(response => response.json())
                    .then(data => {
                        dataLoading.style.display = 'none';

                        if (data.success) {
                            yearSelect.innerHTML = '<option value="">-- 请选择年份 --</option>';
                            data.years.forEach(year => {
                                const option = document.createElement('option');
                                option.value = year;
                                option.textContent = year + '年';
                                yearSelect.appendChild(option);
                            });
                        } else {
                            throw new Error(data.error || '获取年份数据失败');
                        }
                    })
                    .catch(error => {
                        dataLoading.style.display = 'none';
                        console.error('加载年份列表失败:', error);
                        errorMessage.textContent = '加载年份列表失败: ' + error.message;
                        errorMessage.style.display = 'block';
                    });
            }
        });

        // 年份选择变化时启用查询按钮
        yearSelect.addEventListener('change', function() {
            if (this.value) {
                queryBtn.disabled = false;
            } else {
                queryBtn.disabled = true;
            }
        });

        // 查询按钮点击事件
        queryBtn.addEventListener('click', function() {
            const manufacturer = manufacturerSelect.value;
            const model = modelSelect.value;
            const year = yearSelect.value;

            if (!manufacturer || !model || !year) {
                errorMessage.textContent = '请选择厂商、车型和年份';
                errorMessage.style.display = 'block';
                return;
            }

            dataLoading.style.display = 'block';
            errorMessage.style.display = 'none';

            // 执行查询
            fetch(`/api/advanced-query?manufacturer=${encodeURIComponent(manufacturer)}&model=${encodeURIComponent(model)}&year=${year}`)
                .then(response => response.json())
                .then(data => {
                    dataLoading.style.display = 'none';

                    if (data.success) {
                        const result = data.result;

                        // 更新结果
                        document.getElementById('result-manufacturer').textContent = result.manufacturer;
                        document.getElementById('result-model').textContent = result.model;
                        document.getElementById('result-year').textContent = result.year + '年';
                        document.getElementById('result-sales').textContent = result.total_sales.toLocaleString() + ' 台';
                        document.getElementById('result-rank').textContent = result.rank;

                        const changeElement = document.getElementById('result-change');
                        changeElement.innerHTML = result.change_percent;

                        // 根据变化值设置颜色
                        if (result.change_percent.includes('+')) {
                            changeElement.classList.add('increase');
                            changeElement.classList.remove('decrease');
                        } else if (result.change_percent.includes('-')) {
                            changeElement.classList.add('decrease');
                            changeElement.classList.remove('increase');
                        } else {
                            changeElement.classList.remove('increase', 'decrease');
                        }

                        // 显示结果
                        resultContainer.style.display = 'block';
                    } else {
                        throw new Error(data.error || '查询失败');
                    }
                })
                .catch(error => {
                    dataLoading.style.display = 'none';
                    console.error('查询失败:', error);
                    errorMessage.textContent = '查询失败: ' + error.message;
                    errorMessage.style.display = 'block';
                });
        });
    }

function initTop15ManufacturerChart() {
        const chartDom = document.getElementById('top15-manufacturer-chart');
        if (!chartDom) {
            console.error('图表容器未找到');
            return;
        }

        const myChart = echarts.init(chartDom);

        // 显示加载状态
        myChart.showLoading({
            text: '数据加载中...',
            color: '#c23531',
            textColor: '#000',
            maskColor: 'rgba(255, 255, 255, 0.8)'
        });

        // 从后端获取数据
        fetch('/api/top15-manufacturer-data')
           .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
           .then(data => {
                myChart.hideLoading();

                if (data.success) {
                    try {
                        // 解析 JSON 数据并设置图表选项
                        const option = JSON.parse(data.chart_data);
                        myChart.setOption(option);

                        // 窗口大小变化时重绘图表
                        const resizeHandler = () => myChart.resize();
                        window.removeEventListener('resize', resizeHandler);
                        window.addEventListener('resize', resizeHandler);

                        console.log('top15厂商图表加载成功');
                    } catch (parseError) {
                        console.error('解析图表数据失败:', parseError);
                        showError(chartDom, '图表数据解析失败');
                    }
                } else {
                    console.error('获取数据失败:', data.error);
                    showError(chartDom, data.error || '数据获取失败');
                }
            })
           .catch(error => {
                console.error('网络请求失败:', error);
                myChart.hideLoading();
                showError(chartDom, '网络请求失败: ' + error.message);
            });
    }

    function initModelTrendTimelineChart() {
        const chartDom = document.getElementById('model-trend-timeline');
        if (!chartDom) return;
        
        const chart = echarts.init(chartDom);
        chartDom.innerHTML = ''; // 清除可能的错误信息
        chart.showLoading();
        
        fetch('/api/model-trend-timeline')
            .then(res => res.json())
            .then(data => {
                chart.hideLoading();
                if (data.success) {
                    try {
                        // 解析配置并设置图表
                        const option = JSON.parse(data.chart_data);
                        chart.setOption(option);
                        
                        // 添加时间轴播放控制
                        chart.on('timelinechanged', function(params) {
                            console.log('时间轴变化:', params.currentIndex);
                        });
                        
                    } catch (e) {
                        console.error('配置解析错误', e);
                        showError(chartDom, '图表配置解析失败');
                    }
                } else {
                    showError(chartDom, data.error || '数据加载失败');
                }
            })
            .catch(err => {
                chart.hideLoading();
                showError(chartDom, '网络请求失败: ' + err.message);
            });
        
        // 窗口大小调整时重绘
        window.addEventListener('resize', () => chart.resize());
    }

    // 显示错误信息
    function showError(element, message) {
        element.innerHTML = `
            <div class="error-message" style="padding: 20px; color: #f56c6c; background-color: #fef0f0; border-radius: 4px;">
                <i class="bi bi-exclamation-triangle-fill"></i>
                <span>${message}</span>
            </div>
        `;
    }

    // 初始化销售趋势图表 - 增强调试版本
    function initSalesTrendChart() {
        console.log('[SalesTrendChart] 开始初始化');
    
        
        const chartDom = document.getElementById('sales-trend-chart');
        if (!chartDom) {
            console.error('[SalesTrendChart] 未找到图表容器元素');
            return;
        }
        
        // 检查容器尺寸
        const containerRect = chartDom.getBoundingClientRect();
        console.log(`[SalesTrendChart] 容器尺寸: ${containerRect.width} x ${containerRect.height}`);
        
        // 验证ECharts是否正确加载
        if (!window.echarts) {
            chartDom.innerHTML = `
                <div class="error-message">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                    <span>ECharts库加载失败，请检查引用</span>
                </div>
            `;
            console.error('[SalesTrendChart] ECharts库未定义');
            return;
        }
        
        const chart = echarts.init(chartDom);
        
        // 保存原始setOption方法用于调试
        const originalSetOption = chart.setOption;
        chart.setOption = function(option) {
            console.log('[SalesTrendChart] 设置图表选项:', JSON.stringify(option, null, 2));
            return originalSetOption.apply(this, arguments);
        };
        
        chartDom.innerHTML = '';
        chart.showLoading({
            text: '数据加载中...',
            color: '#1890ff',
            textColor: '#000',
            maskColor: 'rgba(255, 255, 255, 0.8)'
        });
        
        console.log('[SalesTrendChart] 开始请求数据');
        
        fetch('/api/sales-trend')
        .then(res => {
                console.log(`[SalesTrendChart] 收到响应: ${res.status} ${res.statusText}`);
                if (!res.ok) {
                    throw new Error(`HTTP错误: ${res.status} ${res.statusText}`);
                }
                return res.json();
            })
        .then(data => {
                console.log('[SalesTrendChart] 数据解析成功:', data);
                chart.hideLoading();
                
                if (!data.success) {
                    const errorMsg = data.details || data.error || '数据加载失败';
                    showError(chartDom, `数据获取失败: ${errorMsg}`);
                    console.error('[SalesTrendChart] 后端错误:', errorMsg);
                    return;
                }
                
                try {
                    const option = data.chart_data;
                     chartDom.innerHTML = `
                        <div style="padding: 10px; margin-bottom: 10px; background-color: #f5f7fa; border-radius: 4px;">
                            <p><strong>数据预览 (前10项):</strong></p>
                            <p>日期: ${option.xAxis.data.slice(0, 10).join(', ')}</p>
                            <p>销量: ${option.series[0].data.slice(0, 10).join(', ')}</p>
                        </div>
                        <div id="echarts-container" style="width:100%; height:450px;"></div>
                    `;
                    const echartsContainer = document.getElementById('echarts-container');
                    const chart = echarts.init(echartsContainer);
                    
                    // 数据验证
                    if (!option || !option.xAxis || !option.yAxis || !option.series) {
                        throw new Error("无效的图表配置格式");
                    }
                    
                    if (!Array.isArray(option.xAxis.data) || option.xAxis.data.length === 0) {
                        throw new Error("X轴数据为空或格式错误");
                    }
                    
                    if (!Array.isArray(option.series[0].data) || option.series[0].data.length === 0) {
                        throw new Error("系列数据为空或格式错误");
                    }
                    
                    console.log(`[SalesTrendChart] 数据验证通过: ${option.xAxis.data.length}个时间点, ${option.series[0].data.length}个数据点`);
                    
                    // 设置图表选项
                    chart.setOption(option);
                    
                    // 检查图表渲染状态
                    setTimeout(() => {
                        const rendered = chart.isDisposed() ? "已销毁" : "已渲染";
                        console.log(`[SalesTrendChart] 渲染状态: ${rendered}`);
                        
                        // 获取图表实际尺寸
                        const chartSize = chart.getDom().getBoundingClientRect();
                        console.log(`[SalesTrendChart] 图表实际尺寸: ${chartSize.width} x ${chartSize.height}`);
                    }, 100);
                    
                    // 窗口大小调整时重绘
                    window.addEventListener('resize', () => {
                        console.log('[SalesTrendChart] 窗口大小改变，重绘图表');
                        chart.resize();
                    });
                    
                    console.log('[SalesTrendChart] 初始化完成');
                    
                } catch (e) {
                    console.error('[SalesTrendChart] 配置解析错误', e);
                    showError(chartDom, `图表配置解析失败: ${e.message}`);
                }
            })
        .catch(err => {
                chart.hideLoading();
                showError(chartDom, `网络请求失败: ${err.message}`);
                console.error('[SalesTrendChart] 网络错误:', err);
            });
    }

    // 在 showPage 函数中添加高级查询页面的初始化
    function showPage(page) {
        // 隐藏所有页面
        document.querySelectorAll('.page-content > div').forEach(el => {
            el.classList.add('d-none');
        });

        // 显示当前页面
        const pageEl = document.getElementById(`${page}-page`);
        if (pageEl) {
            pageEl.classList.remove('d-none');

            // 总览图表
            if (page === 'dashboard' && !window.chartInitialized) {
                initDashboardChart();
            }
            // 车型图表
            if (page === 'model') {
                if (!window.modelChartInitialized) {
                    initModelTop10Chart();
                    window.modelChartInitialized = true;
                }
                if (!window.modelManufacturerChartInitialized) {
                    initModelManufacturerFunnelChart();
                    window.modelManufacturerChartInitialized = true;
                }
                setTimeout(() => {
                if (!window.modelTrendTimelineInitialized) {
                    initModelTrendTimelineChart();
                    window.modelTrendTimelineInitialized = true;
                }
            }, 100);
            }
            // 厂商图表
            if (page === 'manufacturer'){
                if (!window.manufacturerChartInitialized){
                    initTop15ManufacturerChart();
                    window.manufacturerChartInitialized = true;
                }
            }
            // 高级查询页面
            if (page === 'search') {
                initAdvancedQueryPage();
            }
            // 时间趋势页面
            if (page === 'trend') {
                if (!window.salesTrendChartInitialized) {
                    initSalesTrendChart();
                    window.salesTrendChartInitialized = true;
                }
            }
        }
    }

    // 退出登录功能
    function logout() {
        fetch('/logout', {method: 'GET'})
                .then(() => window.location.href = '/login')
                .catch(error => console.error('退出失败:', error));
    }

    // 页面加载完成后初始化仪表盘
    document.addEventListener('DOMContentLoaded', function () {
        initDashboardChart();
    });